package org.yx.controller;

import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.zbus.rpc.RpcClient;
import io.zbus.transport.Message;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yx.context.SystemContext;
import org.yx.service.core.ServiceOut;
import org.yx.utils.Config;
import org.yx.utils.json.Json;

import com.alibaba.fastjson.JSONObject;

@RequestMapping("/service")
public class ServiceController extends JbootController {
	private static Logger logger = LoggerFactory.getLogger(ServiceController.class);

	public void index() {
		String module = getPara("module");

		try {
			RpcClient client = (RpcClient) SystemContext.getBean("rpcClient");
			if (client != null) {
				Map<String, String> headMap = new HashMap<String, String>();
				headMap.put("mq", Config.getString("mq.name"));
				headMap.put("ack", "false");

				Message req = new Message();
				req.setHeaders(headMap);
				req.setUrl(Config.getString("mq.name") + "/" + module + "/" + module);
				req.setBody(new Object[] { JSONObject.toJSON(getParas()) });
				String rspText = Json.beanToJson(client.invoke(req));
				logger.debug(rspText);
				renderJson(rspText);
			} else {
				throw new Exception("Can not find rpcClient define in application.xml.");
			}
		} catch (Throwable t) {
			logger.error(this.getClass().getSimpleName(), t);
			ServiceOut out = new ServiceOut();
			out.setRspCode("BUG-XXXX");
			out.setRspDesc(t.getCause().getMessage());
			renderJson(out);
		}
	}
}
